import { createStore } from 'vuex'
import { getToken, setToken, removeToken } from '@/utils/auth'

export default createStore({
  state: {
    token: getToken(),
    user: null,
    role: null
  },
  mutations: {
    SET_TOKEN(state, token) {
      state.token = token
    },
    SET_USER(state, user) {
      state.user = user
      state.role = user?.role
    },
    CLEAR_USER(state) {
      state.token = null
      state.user = null
      state.role = null
    }
  },
  actions: {
    // 登录
    login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        // 这里应该调用登录API
        // 模拟登录成功
        const token = 'mock-token'
        const user = {
          id: 1,
          username: userInfo.username,
          role: userInfo.username === 'admin' ? 'admin' : 'user'
        }
        
        commit('SET_TOKEN', token)
        commit('SET_USER', user)
        setToken(token)
        resolve(user)
      })
    },
    
    // 登出
    logout({ commit }) {
      commit('CLEAR_USER')
      removeToken()
    }
  },
  getters: {
    isAuthenticated: state => !!state.token,
    isAdmin: state => state.role === 'admin'
  }
}) 